from string import *
import urllib, urllib2, re, random, os, sys, ConfigParser
import xbmc, xbmcgui

sys.path.append(sys.path[0] + '\\lib')
import cachedhttp


try: Emulating = xbmcgui.Emulating
except: Emulating = False

RootDir = os.getcwd()
if RootDir[-1]==';': RootDir=RootDir[0:-1]
if RootDir[-1]!='\\': RootDir=RootDir+'\\'

if not Emulating:
	ROOT_DIR = RootDir
else:
	ROOT_DIR = RootDir
	
saves_folder = RootDir
ImageDir = RootDir + "lib\\"
DatDir = RootDir + "lib\\"
temp_dir = RootDir + "temp\\"
FavoritesFile = saves_folder+"favorites.dat"


cfg = ConfigParser.ConfigParser()
cfg.read(DatDir + 'login.dat')
usrname = cfg.get('Login', 'username')
pasword = cfg.get('Login', 'password')

the_url = 'http://www.ipdirecttv.com/login.php'
the_guide = 'http://www.ipdirecttv.com/members/index.php'
the_dest = RootDir + 'lib\\temp' 
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {'username' : usrname,
		'password' : pasword}


headers = { 'User-Agent' : user_agent }


movies = []
titles = []
desc = []

#############################################################################
# autoscaling values
#############################################################################

HDTV_1080i = 0      #(1920x1080, 16:9, pixels are 1:1)
HDTV_720p = 1       #(1280x720, 16:9, pixels are 1:1)
HDTV_480p_4x3 = 2   #(720x480, 4:3, pixels are 4320:4739)
HDTV_480p_16x9 = 3  #(720x480, 16:9, pixels are 5760:4739)
NTSC_4x3 = 4        #(720x480, 4:3, pixels are 4320:4739)
NTSC_16x9 = 5       #(720x480, 16:9, pixels are 5760:4739)
PAL_4x3 = 6         #(720x576, 4:3, pixels are 128:117)
PAL_16x9 = 7        #(720x576, 16:9, pixels are 512:351)
PAL60_4x3 = 8       #(720x480, 4:3, pixels are 4320:4739)
PAL60_16x9 = 9      #(720x480, 16:9, pixels are 5760:4739)


# Movie class
class Movie:
	def __init__(self, url):
		
		self.url = url
		
def message(line1,line2='',line3=''):
	dialog = xbmcgui.Dialog()
	dialog.ok("Info", line1,line2,line3)
	
def downloader():
	httpFetcher=cachedhttp.CachedHTTPWithProgress() #this class automatically puts up a cancelable progress bar while downloading

	data = urllib.urlencode(values)
	html=httpFetcher.urlopen(the_url, data)
	print html
	httpFetcher.urlretrieve(the_guide,data,the_dest)
	httpFetcher.saveCookies()
	del httpFetcher	
	
def WriteFile(source):
	f = open(DatDir + "temp.dat", 'w')
	f.write(source)
	f.close()

class vidBrowser(xbmcgui.Window):
	def __init__(self):
		
		if Emulating: xbmcgui.Window.__init__(self)
		
		self.setCoordinateResolution(NTSC_4x3)
		self.scaleX = ( float(self.getWidth())  / float(720) )
		self.scaleY = ( float(self.getHeight()) / float(480) )		
		self.count = 0
		self.addControl(xbmcgui.ControlImage(0,0,int(720*self.scaleX),int(480*self.scaleY), ImageDir + "background.png")) 
		self.list = xbmcgui.ControlList(int(50*self.scaleX), int(140*self.scaleX), int(225*self.scaleX), int(300*self.scaleY), 'font13', imageWidth = 75,imageHeight = 75, space = 10 )
		self.movlist = xbmcgui.ControlList(int(295*self.scaleX),int(135*self.scaleY), int(400*self.scaleX), int(300*self.scaleY))
		self.addControl(self.list)
		self.addControl(self.movlist)
		self.lblStatus = xbmcgui.ControlLabel(int(295*self.scaleX), int(400*self.scaleY), int(150*self.scaleX), int(25*self.scaleY), 'No. of Playlist Entries: 0')
		self.addControl(self.lblStatus)
		
		self.PlsBtn = xbmcgui.ControlButton(int(490*self.scaleX), int(45*self.scaleY), int(120*self.scaleX), int(29*self.scaleY), "Play Playlist")		
		self.addControl(self.PlsBtn)
		self.BtnSettings = xbmcgui.ControlButton(int(360*self.scaleX), int(45*self.scaleY), int(120*self.scaleX), int(29*self.scaleY), "Play Playlist")		
		self.addControl(self.BtnSettings)		
		self.createPlaylist()

		
		downloader()
		self.ParseShows()	
		self.ParseMovies('24')		
	
		self.setFocus(self.list)
		
			
		self.movlist.controlLeft(self.list)
		self.list.controlRight(self.movlist)
		self.list.controlLeft(self.PlsBtn)
		self.movlist.controlRight(self.PlsBtn)
		self.PlsBtn.controlDown(self.list)
		
	def onAction(self, action):
		if action.getButtonCode() == 275:
			self.close()
			
		if action.getButtonCode() == 259:
			if self.getFocus() == self.movlist:
				tmpStreamItem = self.movlist.getSelectedPosition()
				self.count = self.count + 1
				print tmpStreamItem
				self.add2Playlist(tmpStreamItem)
				xbmcgui.Dialog().ok('IPDirectTV OD','You Successfully added to','your Playlist.' )
				self.lblStatus.setLabel('No. of Playlist Entries: ' + self.count)
				
						

	def onControl(self, control):
		if control == self.list:
			#if action.GetButtonCode() == 256:
			tmpStreamItem = self.list.getSelectedPosition()
			tmpItem = titles[tmpStreamItem]
			print tmpItem
			self.movlist.reset()
			self.ParseMovies(tmpItem)
				
		if control == self.movlist:
			tmpStreamItem = self.movlist.getSelectedPosition()
			urlMovie = movies[tmpStreamItem]
			self.Play(urlMovie)

			
		if control == self.PlsBtn:
			
			#pls = xbmc.PlayList(2)	## 0 should be music playlist and 2 should be video playlist... not tested      
			#pls.load(DatDir + "viewmovie.m3u")	## load non xbmc playlist into xbmc's playlist  m3u and pls work
			#xbmc.Player().play(pls)	
			self.getPlaylist()
			
		if control == self.BtnSettings:
			s = vidSettings()
			s.doModal()
			del s
			
			
			
	def stripHTML(self,html):
		htmlRe = re.compile('<(.|\n)+?>',re.MULTILINE + re.DOTALL + re.IGNORECASE)
		stripped = htmlRe.sub('',html)
		stripped = self.correctChars(stripped)
		return stripped;		

	def correctChars(self,txt):
		data = txt
		data = replace(data,'&amp;','\'')
		data = replace(data,'&#039;','\'')
		data = replace(data,'&#034;','"')
		data = replace(data,'&amp;;','&')
		data = replace(data,'&#96;',"'")
		data = replace(data,'\n','')
		return data	
		

	def createPlaylist(self):
		f = open(DatDir + "viewmovie.m3u", 'w')
		f.close()

	def add2Playlist(self, num):
		f = open(DatDir + "viewmovie.m3u", 'a')
		pls_src = movies[num]
		print 'The following show was added to the playlist: ' + pls_src
		#ttl_src = desc[num]
		f.write(str(pls_src) + "\r\n")

		f.close()
		
	def getPlaylist(self):
		pls = xbmc.PlayList(1)	## 0 should be music playlist and 2 should be video playlist... not tested      
		
		pls.load(DatDir + "viewmovie.m3u")	## load non xbmc playlist into xbmc's playlist  m3u and pls work
		xbmc.Player().play(pls)	
		
	def Play(self, movie):
	
		if movie == None:
			print('cannot play None object')
			return None
		xbmc.Player().play(movie)
		
	def ParseShows(self):
		f = open(DatDir + "temp.html", 'r')
		toc_src = f.read()
		#reset the show list
		titles[:]
		WriteFile(toc_src)
		#print toc_src
	
		#parse_pattern = re.compile('<div class = "show2">\r\n.\s(.*?).\s</div>') 
		parse_pattern = re.compile('barfix">(.*?) - Playlist Window')
		
		for title in parse_pattern.findall(toc_src):
		
			url = title
			movies.append(url)
			print url
			
			theTitle = title
			tname = str(theTitle)
			name = Movie(theTitle)
			titles.append(tname)	
			
		for t in titles:
			thumb = ImageDir + "tn\\" + str(t) + ".jpg"
			showtitle = xbmcgui.ListItem("    " + t,"" ,"", thumb)	
			self.list.addItem(showtitle)   		
			
	def ParseMovies(self, show):
		del desc[:]
		del movies[:]
		f = open(DatDir + "temp.dat", 'r')
		toc_src = f.read()
		f.close()		
		#print toc_src
		theshow = str(show)
		#print theshow
		#reset the desc list and url list

		regPattern = r"addshow\('" + theshow + "', '.*', '(.*?)', '(.*?)'\)"
		parse_pattern = re.compile(regPattern) 
		
		#print parse_pattern
		
		for link in parse_pattern.findall(toc_src):
		
			url = link[1]
			url2 = 'http://72.36.239.170/view.nsv?id=' + url
			movies.append(url2)
			#print url
			
			theDesc = link[0]
			tname = str(theDesc)
			name = tname
			desc.append(name)	    

		
		movies.reverse()
		desc.reverse()
		
		for d in desc:
			self.movlist.addItem(d)
			

class vidSettings(xbmcgui.WindowDialog):
	def __init__(self):
		if Emulating: xbmcgui.Window.__init__(self)
		
		self.setCoordinateResolution(NTSC_4x3)
		self.scaleX = ( float(self.getWidth())  / float(720) )
		self.scaleY = ( float(self.getHeight()) / float(480) )		
		
		self.addControl(xbmcgui.ControlImage(0,0,int(720*self.scaleX),int(480*self.scaleY), ImageDir + "background_pls.png")) 
		self.username = xbmcgui.ControlTextBox(int(250*self.scaleX), int(200*self.scaleY), int(150*self.scaleX), int(25*self.scaleY), textColor='0xFFFFFFFF')
		self.password = xbmcgui.ControlTextBox(250, 240, 150, 25, textColor='0xFFFFFFFF')
		self.addControl(self.username)
		self.addControl(self.password)
		self.btnOK = xbmcgui.ControlButton(int(300*self.scaleX), int(280*self.scaleY), int(120*self.scaleX), int(29*self.scaleY), "Save")		
		self.addControl(self.btnOK)
		self.setFocus(self.btnOK)		
		self.btnOK.controlUp(self.password)
		self.password.controlUp(self.username)
		self.username.controlUp(self.btnOK)
		self.btnOK.controlDown(self.username)
		self.password.controlDown(self.btnOK)
		self.username.controlDown(self.password)
		
		
	def FillForm(self, user, passw):
			

		cfg.set("Login", "username", user)
		cfg.set("Login", "password", passw)	
		# write to screen
		# config.write(sys.stdout)
		
		
	def onControl(self, control):	
		if control == self.username or self.password:
			keyboard = xbmc.Keyboard('')
			keyboard.doModal()
			tuser = ''
			tpass = ''
			if (keyboard.isConfirmed()):
				self.username.setText(keyboard.getText())
				tuser = keyboard.getText()
			else:
				self.username.setText('none')
				
			keyboard2 = xbmc.Keyboard('')
			keyboard2.doModal()
			if (keyboard2.isConfirmed()):
				self.password.setText(keyboard2.getText())
				tpass = keyboard2.getText()
			else:
				self.password.setText('none')
				
			self.FillForm(tuser,tpass)
			
		if control == self.btnOK:
			self.close()
			
				

w = vidBrowser()
w.doModal()
del w
